import { Component, OnInit, ViewChild, ElementRef, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { StockDataService, StockAlertRule } from '../../shared/services/stock-data.service';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

// 添加Bootstrap类型声明
declare global {
  interface Window {
    bootstrap: {
      Modal: {
        getInstance: (element: HTMLElement) => any;
        new(element: HTMLElement, options?: any): any;
      };
      Tooltip: {
        getInstance: (element: HTMLElement) => any;
        new(element: HTMLElement, options?: any): any;
      };
      Popover: {
        getInstance: (element: HTMLElement) => any;
        new(element: HTMLElement, options?: any): any;
      };
    };
  }
}

@Component({
  selector: 'app-alert-rules',
  templateUrl: './alert-rules.component.html',
  styleUrls: ['./alert-rules.component.scss'],
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule]
})
export class AlertRulesComponent implements OnInit {
  // 预警规则列表
  alertRules: StockAlertRule[] = [];
  
  // 表单
  ruleForm: FormGroup;
  
  // 是否编辑模式
  isEditMode = false;
  
  // 模态框引用
  private modalElement: HTMLElement | null = null;
  private modalInstance: any = null;
  
  // 模态框模板引用
  @ViewChild('ruleFormModal') ruleFormModal!: ElementRef;

  constructor(
    private stockDataService: StockDataService,
    private formBuilder: FormBuilder,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document
  ) {
    // 初始化表单
    this.ruleForm = this.formBuilder.group({
      id: [null],
      isGlobal: [true],
      goodsCode: [''],
      goodsType: [''],
      warehouseName: [''],
      thresholdValue: [10, [Validators.required, Validators.min(0)]],
      priority: [5],
      isActive: [true]
    });
  }

  ngOnInit(): void {
    // 订阅预警规则数据
    this.stockDataService.alertRules$.subscribe(rules => {
      this.alertRules = rules;
    });
  }

  ngAfterViewInit(): void {
    // 初始化模态框
    if (this.ruleFormModal && this.document.defaultView?.bootstrap) {
      this.modalElement = this.ruleFormModal.nativeElement;
      this.modalInstance = new this.document.defaultView.bootstrap.Modal(this.modalElement);
    } else {
      console.error('Bootstrap Modal 初始化失败');
    }
  }

  /**
   * 打开规则表单模态框
   */
  openRuleForm(): void {
    // 重置表单和编辑模式
    this.ruleForm.reset({
      isGlobal: true,
      thresholdValue: 10,
      priority: 5,
      isActive: true
    });
    
    this.isEditMode = false;
    
    // 打开模态框
    if (this.modalInstance) {
      this.modalInstance.show();
    }
  }

  /**
   * 编辑规则
   */
  editRule(rule: StockAlertRule): void {
    // 设置为编辑模式
    this.isEditMode = true;
    
    // 填充表单数据
    this.ruleForm.patchValue({
      id: rule.id,
      isGlobal: rule.isGlobal,
      goodsCode: rule.goodsCode || '',
      goodsType: rule.goodsType || '',
      warehouseName: rule.warehouseName || '',
      thresholdValue: rule.thresholdValue,
      priority: rule.priority,
      isActive: rule.isActive
    });
    
    // 如果是全局规则，禁用特定字段
    if (rule.isGlobal) {
      this.disableSpecificFields();
    } else {
      this.enableSpecificFields();
    }
    
    // 打开模态框
    if (this.modalInstance) {
      this.modalInstance.show();
    }
  }

  /**
   * 删除规则
   */
  deleteRule(id: string): void {
    if (confirm('确定要删除此预警规则吗？')) {
      this.stockDataService.deleteAlertRule(id);
    }
  }

  /**
   * 保存规则
   */
  saveRule(): void {
    if (this.ruleForm.invalid) {
      return;
    }
    
    // 获取表单值
    const formValue = this.ruleForm.value;
    
    // 创建规则对象
    const rule: StockAlertRule = {
      id: formValue.id || '',
      isGlobal: formValue.isGlobal,
      thresholdValue: formValue.thresholdValue,
      priority: formValue.priority,
      isActive: formValue.isActive,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    // 如果不是全局规则，添加特定字段
    if (!formValue.isGlobal) {
      if (formValue.goodsCode) rule.goodsCode = formValue.goodsCode;
      if (formValue.goodsType) rule.goodsType = formValue.goodsType;
      if (formValue.warehouseName) rule.warehouseName = formValue.warehouseName;
    }
    
    // 保存规则
    this.stockDataService.saveAlertRule(rule);
    
    // 关闭模态框
    if (this.modalInstance) {
      this.modalInstance.hide();
    }
  }

  /**
   * 关闭模态框
   */
  closeModal(): void {
    if (this.modalInstance) {
      this.modalInstance.hide();
    }
  }

  /**
   * 规则类型变化处理
   */
  onRuleTypeChange(): void {
    const isGlobal = this.ruleForm.get('isGlobal')?.value;
    
    if (isGlobal) {
      this.disableSpecificFields();
    } else {
      this.enableSpecificFields();
    }
  }

  /**
   * 禁用特定字段
   */
  private disableSpecificFields(): void {
    this.ruleForm.get('goodsCode')?.disable();
    this.ruleForm.get('goodsType')?.disable();
    this.ruleForm.get('warehouseName')?.disable();
    
    // 清空值
    this.ruleForm.patchValue({
      goodsCode: '',
      goodsType: '',
      warehouseName: ''
    });
  }

  /**
   * 启用特定字段
   */
  private enableSpecificFields(): void {
    this.ruleForm.get('goodsCode')?.enable();
    this.ruleForm.get('goodsType')?.enable();
    this.ruleForm.get('warehouseName')?.enable();
  }
} 